#!/usr/bin/env bash
#########################################################################
# File Name   : create_network.sh
# Author      : seadog
# mail        : seadog0514@163.com
# Version     : 0.1
# Created Time: Thu 2024-10-03 14:17:20(+0800)
#########################################################################

#
#
# Usage:

{
  set -euo pipefail

  export TZ="Asia/Shanghai"
  APP_ROOT=$(dirname "$(readlink -fm "$0")")
  cd "${APP_ROOT}"

  exec &> >(tee -a "/tmp/create_network.log")

}

source /root/keystonerc

router_name="r1"

# !!@ router
{
  openstack router create ${router_name}
}

# !!@ geneve
{
  network_name="n1"
  subnet_name="sn1"

  # tenant_network_types = geneve,vxlan
  # 一般不需要指定--provider-segment，由于ovn得限制，启用vxlan得话，就必须指定provider-segment小于4096,
  # 或者配置文件中指定vni_range=1:4096
  openstack network create ${network_name} --provider-network-type geneve --provider-segment 4043

  openstack subnet create ${subnet_name} --network ${network_name} \
    --subnet-range 10.1.1.0/24 --gateway 10.1.1.1 \
    --dns-nameserver 192.168.0.211

  openstack router add subnet ${router_name} ${subnet_name}
}

# !!@ vxlan: ovn default to geneve, no effect here
{
  network_name="n2"
  subnet_name="sn2"

  # tenant_network_types = geneve,vxlan
  # 一般不需要指定--provider-segment，由于ovn得限制，启用vxlan得话，就必须指定provider-segment小于4096,
  # 或者配置文件中指定vni_range=1:4096
  openstack network create ${network_name} --provider-network-type vxlan --provider-segment 4044

  openstack subnet create ${subnet_name} --network ${network_name} \
    --subnet-range 10.2.2.0/24 --gateway 10.2.2.1 \
    --dns-nameserver 192.168.0.211

  openstack router add subnet ${router_name} ${subnet_name}
}

# !!@ external network
# external network 必须先连接一个router，此router连到network n1, 测试连接n1得虚机才可以分配floating ip
{
  external_network_name="e1"
  external_subnet_name="se1"

  openstack network create \
    --provider-physical-network physnet1 \
    --provider-network-type flat --external ${external_network_name}

  openstack subnet create ${external_subnet_name} \
    --network ${external_network_name} \
    --dhcp \
    --subnet-range 192.168.5.0/24 \
    --allocation-pool start=192.168.5.200,end=192.168.5.220 \
    --gateway 192.168.5.2 --dns-nameserver 192.168.0.211

  openstack router set ${router_name} --external-gateway ${external_network_name}
}

# !!@ external network
{
  openstack floating ip list
  openstack floating ip create --floating-ip-address 192.168.5.201 e1
  # openstack server add floating ip cirros1 192.168.5.201
}
